package cn.live.kyle.questionnaire.question;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.w3c.dom.Element;

import cn.live.kyle.questionnaire.R;
import android.content.Context;
import android.text.format.Time;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.DatePicker;
import android.widget.DatePicker.OnDateChangedListener;

public class QuestionDate extends QuestionItem {
	private static final String DATE_FORMAT = "yyyy-MM-dd";

	private DatePicker mDatePicker;

	private int mYear;
	private int mMonth;
	private int mDay;

	public QuestionDate(Element element, QuestionPage page) {
		super(element, page);

		ViewGroup container = page.getQuestionViewContainer();
		Context context = container.getContext();
		mQuestionItemView = LayoutInflater.from(context).inflate(
				R.layout.question_date, container, false);
		mDatePicker = (DatePicker) mQuestionItemView
				.findViewById(R.id.datePicker);

		try {
			String answer = mElement
					.getAttribute(QuestionDomParser.ATTR_ANSWER);
			SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT);
			Date date = format.parse(answer);
			Time time = new Time();
			time.set(date.getTime());
			mYear = time.year;
			mMonth = time.month;
			mDay = time.monthDay;
			mIsAnswered = true;
		} catch (Exception e) {
			Time time = new Time();
			time.set(System.currentTimeMillis());
			mYear = time.year;
			mMonth = time.month;
			mDay = time.monthDay;
			mIsAnswered = true;
		}
		
		saveDate(mYear, mMonth, mDay);

		mDatePicker.init(mYear, mMonth, mDay, new OnDateChangedListener() {
			@Override
			public void onDateChanged(DatePicker view, int year, int month,
					int day) {
				mYear = year;
				mMonth = month;
				mDay = day;
				mIsAnswered = true;

				saveDate(year, month, day);
			}
		});
	}
	
	private void saveDate(int year, int month, int day){
	    Time time = new Time();
        time.set(day, month, year);
        Date date = new Date(time.toMillis(true));
        SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT);
        String answer = format.format(date);
        mElement.setAttribute(QuestionDomParser.ATTR_ANSWER, answer);
	}

}